package nl.scalasim
package actors
package traits

import scala.actors.Actor

/**
 * ComposedActors function as a base-class for actors that are
 * extended with actor traits in this package. It provides a
 * callback list, to which actor traits can add their message handling
 * partial functions. 
 *
 * @author Yigal Duppen
 * @since Oct 4, 2010
 */

class ComposedActor extends Actor
        with Logging
{

  var callbacks = List[PartialFunction[Any, Unit]]()

  /**
   * Fallback handler that just prints the incoming message
   */
  def handleDefault: PartialFunction[Any, Unit] = {
    case m => log.warning("Unknown message: " + m)
  }

  /**
   * Combined function handling all callbacks, excluding handleDefault
   */
  def handleCallbacks: PartialFunction[Any, Unit] = callbacks reduceRight {_ orElse _}

  /**
   * By default, tries all callbacks and falls back on handleDefault
   */
  def act() = {
    loop {
      react {
        handleCallbacks orElse handleDefault
      }
    }
  }

}